package cn.lcsjsxy.yxz.day.Practice.Thread;
//生产者消费者问题
public class Practice3 {
    public static void main(String[] args) {

        // 使用 wait () 和 notify () 实现一个简单的生产者消费者模型，
        // 生产者生产数据放入缓冲区，消费者从缓冲区取出数据。

        ProducerConsumer pc = new ProducerConsumer();
        //生产
        Thread producer = new Thread(() -> {
            for (int i = 1; i <= 10; i++){
                try {
                    pc.produce(i);
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        //消费
        Thread consumer = new Thread(() ->{
            for (int i = 1; i <= 10; i++){
                try {
                    pc.consume();
                    Thread.sleep(300);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        //输出
        producer.start();
        consumer.start();
    }
}
class ProducerConsumer {
    private static final int BUFFER_SIZE = 5;
    private int[] buffer = new int[BUFFER_SIZE];
    private int count = 0;
    private int in = 0;
    private int out = 0;

    //生产
    public synchronized void produce(int value) throws InterruptedException{
        //缓冲
        while (count == BUFFER_SIZE){
            wait();
        }
        buffer[in] = value;
        in = (in + 1) % BUFFER_SIZE;
        count++;
        System.out.println("生产: " + value + ",缓冲区的大小: " + count);
        //通知
        notify();
    }
    //消费
    public synchronized int consume() throws InterruptedException{
        //缓冲
        while (count == 0){
            wait();
        }
        int value = buffer[out];
        out = (out + 1) % BUFFER_SIZE;
        count--;
        System.out.println("消费: " + value + ",缓冲区的大小: " + count);
        //通知
        notify();

        return value;
    }
}